import { ref, computed, onMounted, onUnmounted } from 'vue'

/**
 * 响应式设计组合式函数
 * @returns {Object} 响应式状态和方法
 */
export function useResponsive() {
  // 屏幕尺寸
  const windowWidth = ref(window.innerWidth)
  const windowHeight = ref(window.innerHeight)

  // 断点定义
  const breakpoints = {
    xs: 480,
    sm: 768,
    md: 992,
    lg: 1200,
    xl: 1920
  }

  // 更新窗口尺寸
  const updateSize = () => {
    windowWidth.value = window.innerWidth
    windowHeight.value = window.innerHeight
  }

  // 计算属性
  const currentBreakpoint = computed(() => {
    const width = windowWidth.value
    if (width < breakpoints.xs) return 'xs'
    if (width < breakpoints.sm) return 'sm'
    if (width < breakpoints.md) return 'md'
    if (width < breakpoints.lg) return 'lg'
    return 'xl'
  })

  const isXs = computed(() => windowWidth.value < breakpoints.xs)
  const isSm = computed(() => windowWidth.value >= breakpoints.xs && windowWidth.value < breakpoints.sm)
  const isMd = computed(() => windowWidth.value >= breakpoints.sm && windowWidth.value < breakpoints.md)
  const isLg = computed(() => windowWidth.value >= breakpoints.md && windowWidth.value < breakpoints.lg)
  const isXl = computed(() => windowWidth.value >= breakpoints.lg)

  const isMobile = computed(() => windowWidth.value < breakpoints.sm)
  const isTablet = computed(() => windowWidth.value >= breakpoints.sm && windowWidth.value < breakpoints.md)
  const isDesktop = computed(() => windowWidth.value >= breakpoints.md)

  const isPortrait = computed(() => windowHeight.value > windowWidth.value)
  const isLandscape = computed(() => windowWidth.value > windowHeight.value)

  // 响应式列数
  const getResponsiveColumns = (config = {}) => {
    const defaultConfig = {
      xs: 1,
      sm: 2,
      md: 3,
      lg: 4,
      xl: 5
    }
    
    const finalConfig = { ...defaultConfig, ...config }
    return computed(() => finalConfig[currentBreakpoint.value])
  }

  // 响应式间距
  const getResponsiveSpacing = (config = {}) => {
    const defaultConfig = {
      xs: 8,
      sm: 12,
      md: 16,
      lg: 20,
      xl: 24
    }
    
    const finalConfig = { ...defaultConfig, ...config }
    return computed(() => finalConfig[currentBreakpoint.value])
  }

  // 响应式字体大小
  const getResponsiveFontSize = (config = {}) => {
    const defaultConfig = {
      xs: 12,
      sm: 14,
      md: 16,
      lg: 18,
      xl: 20
    }
    
    const finalConfig = { ...defaultConfig, ...config }
    return computed(() => `${finalConfig[currentBreakpoint.value]}px`)
  }

  // 生命周期
  onMounted(() => {
    window.addEventListener('resize', updateSize)
  })

  onUnmounted(() => {
    window.removeEventListener('resize', updateSize)
  })

  return {
    // 尺寸
    windowWidth,
    windowHeight,
    
    // 断点
    breakpoints,
    currentBreakpoint,
    
    // 断点判断
    isXs,
    isSm,
    isMd,
    isLg,
    isXl,
    
    // 设备类型
    isMobile,
    isTablet,
    isDesktop,
    
    // 方向
    isPortrait,
    isLandscape,
    
    // 工具方法
    getResponsiveColumns,
    getResponsiveSpacing,
    getResponsiveFontSize
  }
}

/**
 * 媒体查询组合式函数
 * @param {string} query 媒体查询字符串
 * @returns {Object} 匹配状态
 */
export function useMediaQuery(query) {
  const matches = ref(false)
  let mediaQuery = null

  const updateMatches = () => {
    matches.value = mediaQuery.matches
  }

  onMounted(() => {
    mediaQuery = window.matchMedia(query)
    matches.value = mediaQuery.matches
    mediaQuery.addEventListener('change', updateMatches)
  })

  onUnmounted(() => {
    if (mediaQuery) {
      mediaQuery.removeEventListener('change', updateMatches)
    }
  })

  return { matches }
}

/**
 * 触摸设备检测
 * @returns {Object} 触摸设备状态
 */
export function useTouchDevice() {
  const isTouchDevice = computed(() => {
    return 'ontouchstart' in window || 
           navigator.maxTouchPoints > 0 || 
           navigator.msMaxTouchPoints > 0
  })

  const hasHover = computed(() => {
    return window.matchMedia('(hover: hover)').matches
  })

  const hasPointer = computed(() => {
    return window.matchMedia('(pointer: fine)').matches
  })

  return {
    isTouchDevice,
    hasHover,
    hasPointer
  }
}

/**
 * 屏幕方向检测
 * @returns {Object} 屏幕方向状态
 */
export function useOrientation() {
  const orientation = ref(screen.orientation?.angle || 0)
  const type = ref(screen.orientation?.type || 'portrait-primary')

  const updateOrientation = () => {
    orientation.value = screen.orientation?.angle || 0
    type.value = screen.orientation?.type || 'portrait-primary'
  }

  onMounted(() => {
    if (screen.orientation) {
      screen.orientation.addEventListener('change', updateOrientation)
    } else {
      window.addEventListener('orientationchange', updateOrientation)
    }
  })

  onUnmounted(() => {
    if (screen.orientation) {
      screen.orientation.removeEventListener('change', updateOrientation)
    } else {
      window.removeEventListener('orientationchange', updateOrientation)
    }
  })

  const isPortrait = computed(() => type.value.includes('portrait'))
  const isLandscape = computed(() => type.value.includes('landscape'))

  return {
    orientation,
    type,
    isPortrait,
    isLandscape
  }
}

/**
 * 视口尺寸检测
 * @returns {Object} 视口信息
 */
export function useViewport() {
  const { windowWidth, windowHeight } = useResponsive()

  const viewportWidth = computed(() => windowWidth.value)
  const viewportHeight = computed(() => windowHeight.value)
  const aspectRatio = computed(() => viewportWidth.value / viewportHeight.value)

  const isWideScreen = computed(() => aspectRatio.value > 1.5)
  const isSquareScreen = computed(() => Math.abs(aspectRatio.value - 1) < 0.2)
  const isTallScreen = computed(() => aspectRatio.value < 0.8)

  return {
    viewportWidth,
    viewportHeight,
    aspectRatio,
    isWideScreen,
    isSquareScreen,
    isTallScreen
  }
}

/**
 * 响应式网格系统
 * @param {Object} config 网格配置
 * @returns {Object} 网格状态
 */
export function useResponsiveGrid(config = {}) {
  const { currentBreakpoint } = useResponsive()

  const defaultConfig = {
    xs: { columns: 1, gap: 8 },
    sm: { columns: 2, gap: 12 },
    md: { columns: 3, gap: 16 },
    lg: { columns: 4, gap: 20 },
    xl: { columns: 5, gap: 24 }
  }

  const gridConfig = { ...defaultConfig, ...config }

  const columns = computed(() => gridConfig[currentBreakpoint.value].columns)
  const gap = computed(() => gridConfig[currentBreakpoint.value].gap)

  const gridStyle = computed(() => ({
    display: 'grid',
    gridTemplateColumns: `repeat(${columns.value}, 1fr)`,
    gap: `${gap.value}px`
  }))

  return {
    columns,
    gap,
    gridStyle
  }
}

/**
 * 响应式表格
 * @param {Array} columns 表格列配置
 * @returns {Object} 表格状态
 */
export function useResponsiveTable(columns = []) {
  const { isMobile, isTablet } = useResponsive()

  const visibleColumns = computed(() => {
    if (isMobile.value) {
      // 移动端只显示重要列
      return columns.filter(col => col.important !== false).slice(0, 2)
    } else if (isTablet.value) {
      // 平板端显示部分列
      return columns.filter(col => col.hideOnTablet !== true)
    } else {
      // 桌面端显示所有列
      return columns
    }
  })

  const tableLayout = computed(() => {
    if (isMobile.value) {
      return 'card' // 卡片布局
    } else {
      return 'table' // 表格布局
    }
  })

  return {
    visibleColumns,
    tableLayout,
    isMobile,
    isTablet
  }
}

/**
 * 响应式导航
 * @returns {Object} 导航状态
 */
export function useResponsiveNavigation() {
  const { isMobile, isTablet } = useResponsive()
  const isCollapsed = ref(false)

  const navigationMode = computed(() => {
    if (isMobile.value) {
      return 'drawer' // 抽屉模式
    } else if (isTablet.value) {
      return 'collapse' // 折叠模式
    } else {
      return 'full' // 完整模式
    }
  })

  const toggleCollapse = () => {
    isCollapsed.value = !isCollapsed.value
  }

  return {
    navigationMode,
    isCollapsed,
    toggleCollapse,
    isMobile,
    isTablet
  }
}



